package cn.tk.resource;

import cn.tk.resource.loader.ResLoader;
import cn.tk.utils.EmptyUtil;
import lombok.Getter;
import lombok.Setter;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * Created by denglw on 2021/5/27.<br/>
 * Desc: 接口授权白名单
 */
public class AppWhiteList {

    /**
     * 白名单列表
     */
    private final List<WhiteItem> whiteList = new ArrayList<>();

    private AppWhiteList() {
        this.load();
    }

    public static AppWhiteList of() {
        return AppWhiteList.SingletonHolder.INSTANCE;
    }

    private static class SingletonHolder {
        private static final AppWhiteList INSTANCE = new AppWhiteList();
    }

    /**
     * 初始化加载
     */
    private void load() {
        List<String> lines = ResLoader.readLines("app-white-list.txt");
        if (lines == null) {
            return;
        }
        whiteList.clear();
        for (String line : lines) {
            String[] split = line.split("@");
            if (split.length != 2) {
                continue;
            }
            whiteList.add(new WhiteItem(split[0], split[1]));
        }
    }

    /**
     * 检验用户是否在白名单中.<br/>
     * @param appId 用户
     * @return bool
     */
    public boolean existAppId(String appId) {
        if (EmptyUtil.blank(appId)) {
            return false;
        }
        for (WhiteItem item : whiteList) {
            boolean match = Objects.equals(item.getAppId(), appId);
            if (match) {
                return true;
            }
        }
        return false;
    }

    public String appSecret(String appId) {
        if (EmptyUtil.blank(appId)) {
            return "";
        }
        for (WhiteItem item : whiteList) {
            boolean match = Objects.equals(item.getAppId(), appId);
            if (match) {
                return item.getAppSecret();
            }
        }
        return "";
    }

    @Getter @Setter
    static class WhiteItem {
        private String appId;
        private String appSecret;

        WhiteItem(String appId, String appecret) {
            this.appId = appId;
            this.appSecret = appecret;
        }
    }

}
